package nix.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.junit.Test;

public class Test2 {

	public void updateBalance(Connection con, String name, int balance) {
		PreparedStatement pstmt = null;
		try {
			String sql = "update account set balance = balance + ? where name = ?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, balance);
			pstmt.setString(2, name);
			pstmt.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				pstmt.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}

	public void transfer(String from, String to, int amount) {
		Connection con = null;
		try {
			con = JdbcUtils.getConnection();
			con.setAutoCommit(false);

			updateBalance(con, from, -amount);
			if (true) {
				throw new RuntimeException("中间出错了！");
			}
			updateBalance(con, to, amount);

			con.commit();
		} catch (Exception e) {
			try {
				con.rollback();
			} catch (Exception e1) {
			}
			throw new RuntimeException(e);
		} finally {
			try {
				con.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Test
	public void fun1() {

		transfer("zs", "ww", 100);
	}
}
